package bll

import (
	"context"
	"github.com/LyricTian/gin-admin/v7/internal/app/schema"
	"github.com/LyricTian/gin-admin/v7/internal/lib/pay"
)

func AddMap(args map[string]string, key, value string) map[string]string {
	for k, _ := range args {
		if k == key {
			return args
		}
	}

	args[key] = value
	return args
}

func (a *Order) WeAppPay(ctx context.Context, openId string, money int) (*pay.OderInfo, error) {
	data, err := a.SetModel.Query(ctx, schema.SetQueryParam{Category: "wechat"})
	if err != nil {
		return nil, err
	}
	m := data.Data.GetCategory("wechat")

	isAutoCreate := len(m) == 0
	//appId := "wxf15ca6b36679efd3"
	//mchId := "1395742102"
	//apiKey := "sdfs35d4fgd3f2FG41d3f245gd3fg54d"
	//notifyUrl := "http://www.geiliyigou.com/"
	//wapUrl := "http://www.geiliyigou.com/"

	m = AddMap(m, "app_id", "wxf15ca6b36679efd3")
	m = AddMap(m, "secret", "sdfs35d4fgd3f2FG41d3f245gd3fg54d")
	m = AddMap(m, "mch_id", "1395742102")
	m = AddMap(m, "api_key", "sdfs35d4fgd3f2FG41d3f245gd3fg54d")
	m = AddMap(m, "return_url", "http://www.geiliyigou.com/")
	m = AddMap(m, "notify_url", "http://www.geiliyigou.com/")
	m = AddMap(m, "wap_url", "http://www.geiliyigou.com/")

	m = AddMap(m, "cert_file_path", "")
	m = AddMap(m, "key_file_path", "")
	m = AddMap(m, "pkcs12_file_path", "")

	if isAutoCreate {
		ms := make(schema.MapSet)
		ms["wechat"] = m
		a.SetBll.MapToSet(ctx, 1, "root", ms)
	}
	//appId := "wxf15ca6b36679efd3"
	//mchId := "1395742102"
	//apiKey := "sdfs35d4fgd3f2FG41d3f245gd3fg54d"
	//notifyUrl := "http://www.geiliyigou.com/"
	//wapUrl := "http://www.geiliyigou.com/"
	//isProd := true

	p := pay.NewWeChatPay(&pay.WeChatPayConfig{
		Appid:          m["app_id"],
		MchId:          m["mch_id"],
		ApiKey:         m["api_key"],
		IsProd:         true,
		CertFilePath:   "",
		KeyFilePath:    "",
		Pkcs12FilePath: "",
		NotifyUrl:      m["notify_url"],
		ReturnUrl:      m["return_url"],
		WapUrl:         m["wap_url"],
	})

	return p.WeAppUnifiedOrder(money, openId)

}
